﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;

namespace OrderManagement
{
    public class OrderService
    {
        private List<Order> orders;

        public OrderService()
        {
            orders = new List<Order>();
        }

        public void AddOrder(Order order)
        {
            if (orders.Any(o => o.Equals(order)))
            {
                throw new ArgumentException($"订单已存在: {order.OrderId}");
            }
            orders.Add(order);
        }

        public void DeleteOrder(string orderId)
        {
            var order = orders.FirstOrDefault(o => o.OrderId == orderId);
            if (order == null)
            {
                throw new ArgumentException($"订单不存在: {orderId}");
            }
            orders.Remove(order);
        }

        public void UpdateOrder(Order updatedOrder)
        {
            var index = orders.FindIndex(o => o.OrderId == updatedOrder.OrderId);
            if (index == -1)
            {
                throw new ArgumentException($"订单不存在: {updatedOrder.OrderId}");
            }
            orders[index] = updatedOrder;
        }

        public List<Order> QueryByOrderId(string orderId)
        {
            return orders
                .Where(o => o.OrderId.Contains(orderId))
                .OrderByDescending(o => o.TotalAmount)
                .ToList();
        }

        public List<Order> QueryByProductName(string productName)
        {
            return orders
                .Where(o => o.Details.Any(d => d.ProductName.Contains(productName)))
                .OrderByDescending(o => o.TotalAmount)
                .ToList();
        }

        public List<Order> QueryByCustomer(string customer)
        {
            return orders
                .Where(o => o.Customer.Contains(customer))
                .OrderByDescending(o => o.TotalAmount)
                .ToList();
        }

        public List<Order> QueryByAmountRange(double min, double max)
        {
            return orders
                .Where(o => o.TotalAmount >= min && o.TotalAmount <= max)
                .OrderByDescending(o => o.TotalAmount)
                .ToList();
        }

        public List<Order> GetAllOrders()
        {
            return orders
                .OrderByDescending(o => o.TotalAmount)
                .ToList();
        }

        public void SortOrders()
        {
            orders.Sort((x, y) => string.Compare(x.OrderId, y.OrderId, StringComparison.Ordinal));
        }

        public void SortOrders(Comparison<Order> comparison)
        {
            orders.Sort(comparison);
        }

        public void Export(string filePath)
        {
            try
            {
                using (var writer = new StreamWriter(filePath))
                {
                    var serializer = new XmlSerializer(typeof(List<Order>));
                    serializer.Serialize(writer, orders);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"导出订单失败: {ex.Message}", ex);
            }
        }

        public void Import(string filePath)
        {
            try
            {
                if (!File.Exists(filePath))
                {
                    throw new FileNotFoundException($"文件不存在: {filePath}");
                }

                using (var reader = new StreamReader(filePath))
                {
                    var serializer = new XmlSerializer(typeof(List<Order>));
                    orders = (List<Order>)serializer.Deserialize(reader);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"导入订单失败: {ex.Message}", ex);
            }
        }
    }
}